package netty.server;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.util.Date;

@Slf4j
@ChannelHandler.Sharable
public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {

    public TelnetServerHandler() {
        log.info(">>> init {}", this.toString());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
        ctx.write("It is " + new Date() + " now.\r\n");
        ctx.flush();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        try {
            // Do something with msg
            log.info("receive data: {}, {}", msg, ctx.channel().remoteAddress());

            if (msg.equalsIgnoreCase("exit")
                    || msg.equalsIgnoreCase("quite")
                    || msg.equalsIgnoreCase("bye")) {
                ctx.writeAndFlush(">>> client will quit\n").addListener(ChannelFutureListener.CLOSE);
            }
            ctx.writeAndFlush(msg + "\n");
        } finally {
//            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}